# PLUGIN_NAME = SVN
# $in CHECKOUT or CLEANUP
# $in project address
# $in project name
# $in checkout directory

use strict;
use Config::INIPlus;
use Cwd;

if( scalar(@ARGV) != 4 )
{
	exit 1; 
}

my $this_script_path = Cwd::abs_path( $0 );
my @path_array = split /\//, $this_script_path;
$path_array[$#path_array] = "svn.cfg";
my $config_file_path = join '\\', @path_array;

my $method = $ARGV[0];
my $project_address = $ARGV[1];
my $project_name = $ARGV[2];
my $checkout_dir = $ARGV[3];
my %config;

if( $method eq "CHECKOUT" )
{
	exit Checkout();
}
elsif( $method eq "CLEANUP" )
{
	exit CleanUp();
}
else
{
	exit 1;
}

# $out 0 for success, 1 for failure
sub Checkout()
{
	
	my $cfg = Config::INIPlus->new( file => $config_file_path );
	$config{"svn_path"}  = $cfg->get( "SVN_PATH", "MAIN" );


	chdir( $checkout_dir );

	# if there is already the project
	if( -d $project_name )
	{
		return Update();
	}
	else
	{
		return CheckoutNew();
	}
}

sub CheckoutNew()
{
	my $cmd = "\"" . $config{"svn_path"} . "\"";
	$cmd .= " checkout";
	$cmd .= " \"" . $project_address . "\"";
	$cmd .= " \"" . $project_name . "\"";

#	print "$cmd\n";

	open( OUTPUT, "$cmd|" );

	my $line;
	my $succeeded = 0;
	while ( $line = <OUTPUT> )
	{
		chomp $line;
		print "OUTPUT> $line\n";
		if ( $line =~ /Checked out revision/ )
		{
			$succeeded = 1;
		}
	}

	if( $succeeded )
	{
		print "SUCCEEDED\n";
		return 0;
	}
	else
	{
		print "FAILED\n";
		return 1;
	}

}

sub Update()
{

	chdir( $project_name );

	my $cmd = "\"" . $config{"svn_path"} . "\"";
	$cmd .= " update";

	print "$cmd\n";

	open( OUTPUT, "$cmd|" );

	my $line;
	my $succeeded = 0;
	while ( $line = <OUTPUT> )
	{
		chomp $line;
		print "OUTPUT> $line\n";

		if ( $line =~ /At revision/ )
		{
			print "SKIP\n";
			return 0;
		}
		elsif ( $line =~ /Updated to revision/ )
		{
			print "SUCCEEDED\n";
			return 0;
		}
	}

	print "FAILED\n";
	return 1;
}

# $out 0 for success, 1 for failure
sub CleanUp()
{
	# TODO

}





